<template>
  <el-drawer v-model="visible" :show-close="false" width="30%" append-to-body @close="handleClose">
    <template #header>
      <div class="flex-x-between">
        <span>规格管理</span>
        <el-button type="primary" link size="small" icon="plus" @click="handleAddSpecTag">
          新增
        </el-button>
      </div>
    </template>
    <BasePageTable
      :tableData="tableData"
      :loading="loading"
      :pageNum="queryPage.pageNum"
      :pageSize="queryPage.pageSize"
      :total="queryPage.total"
      :tableColumnsData="tableColumnsData"
      @handleQuery="handleQuery"
    >
      <template #tags="scope">
        <div class="flex flex-wrap">
          <el-tag v-for="tag in scope.row.tags" :key="tag" size="small" type="primary" class="mr-2">
            {{ tag }}
          </el-tag>
        </div>
      </template>
      <template #handle="scope">
        <el-button type="primary" link size="small" icon="edit" @click.stop="handleEdit(scope.row)">
          编辑
        </el-button>
        <el-button
          type="danger"
          link
          size="small"
          icon="delete"
          @click.stop="handleDelete(scope.row)"
        >
          删除
        </el-button>
      </template>
    </BasePageTable>
  </el-drawer>
  <!-- 属性的弹框 -->
  <el-dialog v-model="specTagVisible" :title="specTagTitle" width="30%">
    <el-form
      :model="specTagFormData"
      :rules="specTagRules"
      label-width="100px"
      ref="specTagFormRef"
    >
      <el-form-item label="属性名称" prop="name">
        <el-input v-model="specTagFormData.name" placeholder="请输入属性名称" maxlength="20" />
      </el-form-item>
      <el-form-item label="规格" prop="tags">
        <EditTags v-model="specTagFormData.tags" :tags="activeTags" :canSwitch="false" />
      </el-form-item>
      <div class="flex-x-end">
        <el-form-item>
          <el-button type="primary" @click="submitAddSpecTag">确认</el-button>
        </el-form-item>
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup>
import EditTags from "./EditTags.vue";
import EquityMallAPI from "@/api/equitymall";
const props = defineProps({
  specTypeOptions: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(["updateSpecTag"]);
const visible = ref(false);
// 关闭弹窗
const handleClose = () => {
  visible.value = false;
};
const openDialog = async () => {
  visible.value = true;
};
const queryPage = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const activeTags = computed(() => {
  return (
    activeSpecTag.value?.tags?.map((item) => {
      return { id: item, name: item };
    }) || []
  );
});
const tableData = ref([]);
const loading = ref(false);
const tableColumnsData = ref([
  {
    label: "属性名称",
    prop: "name",
    align: "center",
  },
  {
    label: "规格",
    prop: "tags",
    customSlot: "tags",
    align: "center",
  },
  {
    label: "操作",
    prop: "handle",
    customSlot: "handle",
    align: "center",
    showOverflowTooltip: true,
  },
]);
const handleQuery = () => {
  console.log("handleQuery");
};
const specTagTitle = ref("");
const handleEdit = (row) => {
  console.log(row, "编辑");
  activeSpecTag.value = {};
  specTagVisible.value = true;
  specTagFormData.value.name = row.name;
  specTagFormData.value.tags = row.tags.map((item) => ({ id: item, name: item }));
  specTagTitle.value = "编辑属性";
  activeSpecTag.value = row;
};
const handleDelete = (row) => {
  console.log(row, "删除");
  ElMessageBox.confirm("确定要删除属性吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteProductProperty(row.id);
  });
};

// 当前操作的属性
const activeSpecTag = ref({});
const specTagVisible = ref(false);
const specTagFormData = ref({
  name: "",
});
const specTagRules = ref({
  name: [{ required: true, message: "请输入属性名称", trigger: "blur" }],
});
const handleAddSpecTag = () => {
  specTagTitle.value = "新增属性";
  specTagVisible.value = true;
  activeSpecTag.value = {};
  specTagFormData.value.name = "";
  specTagFormData.value.tags = [];
};
const specTagFormRef = ref(null);
// 新增或者编辑属性
const submitAddSpecTag = () => {
  specTagFormRef.value.validate((valid) => {
    let params = {
      id: activeSpecTag.value.id,
      name: specTagFormData.value.name,
      tags: specTagFormData.value.tags.map((item) => item.name).join(","),
    };
    if (valid) {
      if (specTagTitle.value === "新增属性") {
        addProductProperty();
      } else {
        editProductProperty();
      }
    }
  });
};
// 编辑属性
const editProductProperty = async () => {
  try {
    let params = {
      id: activeSpecTag.value.id,
      name: specTagFormData.value.name,
      tags: specTagFormData.value.tags.map((item) => item.name).join(","),
    };
    await EquityMallAPI.editProductProperty(params);
    ElMessage.success("编辑成功");
    specTagVisible.value = false;
    emit("updateSpecTag");
  } catch (error) {
    console.error(error);
  }
};
// 新增属性
const addProductProperty = async () => {
  let params = {
    name: specTagFormData.value.name,
    tags: specTagFormData.value.tags.map((item) => item.name).join(","),
  };
  try {
    const res = await EquityMallAPI.addProductProperty(params);
    ElMessage.success("新增成功");
    specTagVisible.value = false;
    emit("updateSpecTag");
  } catch (error) {
    console.error(error);
  }
};
// 删除属性
const deleteProductProperty = async (id) => {
  try {
    const res = await EquityMallAPI.deleteProductProperty(id);
    ElMessage.success("删除成功");
    emit("updateSpecTag");
  } catch (error) {
    console.error(error);
  }
};
watchEffect(async () => {
  tableData.value = props.specTypeOptions.map((item) => ({
    id: item.id,
    name: item.name,
    tags: item?.tags?.split(",") || [],
  }));
});
defineExpose({
  openDialog,
});
</script>

<style scoped>
.notice-content {
  width: 100%;
  overflow-x: hidden;
}

/* 由于 v-html 内容不受 scoped 样式影响，需要使用 :deep() */
:deep(.notice-content img) {
  max-width: 100%;
  height: auto;
}
</style>
